﻿using Home.Domain.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities.Validation;
using Utilities.ViewModel;
using Omu.ValueInjecter;
using System.Data;

namespace Home.WebUI.Areas.Mythi.Controllers
{
    [Home.WebUI.Areas.NewAdmin.Models.AdminLogin]
    public class SuccessController : Controller
    {
        #region 基本
        private EFDbContext db = new EFDbContext();
        private DbSet<Success> MEntity
        {
            get { return db.Successes; }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
        //
        // GET: /Mythi/Success/

        public ActionResult Index(PagedList<Success> model, int page = 1)
        {
            //页面项数
            const int pageSize = 10;
            var list = MEntity.Include(t => t.LeiBie).Include(t=>t.Brand).OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                list = list.Where(c => c.Name.Contains(model.Search));
            }
            model.Entities = list;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = MEntity.Count() };
            return View(model);
        }

        public ActionResult Create()
        {
            SuccessCreate model = new SuccessCreate();
            model.CreateDate = DateTime.Now;
            DDLBrand();
            DDLLeiBie();
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(SuccessCreate model, HttpPostedFileBase pic)
        {
            //try
            //{
            if (model.UniValidate.CheckAll(Request))
            {
                bool up = false;
                model.Pic = Utilities.Common.UpLoad(pic, "img", 2 * 1024, "/Upload/Images/", 1, ref up);
                if (!up)
                {
                    TempData["Tip"] = new TipModel(1, model.Pic);
                    DDLBrand(model.BrandId);
                    DDLLeiBie(model.LeiBieId);
                    return View(model);
                }
                Success content = new Success();
                content.InjectFrom(model);
                MEntity.Add(content);
                db.SaveChanges();
                TempData["Tip"] = new TipModel(1, "新建成功");
                return RedirectToAction("Index");
            }
            //}
            //catch (DataException)
            //{
            //    TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            //}
            DDLBrand(model.BrandId);
            DDLLeiBie(model.LeiBieId);
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var model = new SuccessCreate();
            model.InjectFrom(MEntity.Find(id));
            DDLBrand(model.BrandId);
            DDLLeiBie(model.LeiBieId);
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(SuccessCreate model, HttpPostedFileBase pic)
        {
            try
            {
                if (model.UniValidate.CheckAll(Request))
                {
                    var content = new Success();
                    content.Id = model.Id;
                    MEntity.Attach(content);
                    content.InjectFrom(model);
                    if (pic != null)
                    {
                        bool up = false;
                        string Pic = Utilities.Common.UpLoad(pic, "img", 2 * 1024, "/Upload/Images/", 1, ref up);
                        if (!up)
                        {
                            TempData["Tip"] = new TipModel(1, Pic);
                            DDLBrand(model.BrandId);
                            DDLLeiBie(model.LeiBieId);
                            return View(model);
                        }
                        content.Pic = Pic;
                    }
                    
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Edit", new { id = model.Id });
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            DDLBrand(model.BrandId);
            DDLLeiBie(model.LeiBieId);
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    var content = MEntity.Find(id);
                    MEntity.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }

        private void DDLLeiBie(int? id = null)
        {
            ViewBag.LeiBieId = new SelectList(db.LeiBies.OrderBy(t => t.Sort).ToList(), "Id", "Title", id);
        }
        private void DDLBrand(int? id = null)
        {
            ViewBag.BrandId = new SelectList(db.Brands.OrderBy(t => t.Sort).ToList(), "Id", "Title", id);
        }

    }
    #region 验证类
    public class SuccessCreate
    {
        public int Id { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Body { get; set; }
        /// <summary>
        /// 图片
        /// </summary>
        [MaxLength(200)]
        public string Pic { get; set; }
        /// <summary>
        /// 排序
        /// </summary>
        public int Sort { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateDate { get; set; }

        public int BrandId { get; set; }

        public int LeiBieId { get; set; }
        public UniValidate UniValidate
        {
            get
            {
                var uv = new UniValidate();
                uv.InitName(() => Name).NotEmpty().MaxLength(36);
                uv.InitName(() => Body).NotEmpty();
                uv.InitName(() => BrandId).NotEmpty();
                uv.InitName(() => LeiBieId).NotEmpty();
                uv.InitName(() => CreateDate).NotEmpty().DateTimeOrDate();
                uv.ValidEnd(".form-horizontal");
                return uv;
            }
        }
    }
    #endregion
}
